from flask import jsonify, request, render_template, Blueprint
from sqlalchemy.exc import IntegrityError

from tzq.extensions import db

fspl_crud_bp = Blueprint(
    'fspl_crud',
    __name__,
    url_prefix='/fspl_crud',
    template_folder='templates'  # 指定蓝图专属模板目录
)


# 定义数据模型
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)
    stock = db.Column(db.Integer, nullable=False)


# 前端页面 /fspl_crud/fspl_crud_index
@fspl_crud_bp.route('/fspl_crud_index')
def fspl_crud_index():
    return render_template('fspl_crud_index.html')


# 获取数据接口 (Layui表格格式)
@fspl_crud_bp.route('/api/products', methods=['GET'])
def get_products():
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    search_key = request.args.get('key', '')

    # 查询和分页
    query = Product.query
    if search_key:
        query = query.filter(Product.name.ilike(f'%{search_key}%'))

    pagination = query.paginate(page=page, per_page=limit, error_out=False)

    # 构建Layui表格要求的数据格式
    return jsonify({
        "code": 0,
        "msg": "",
        "count": pagination.total,
        "data": [{
            "id": item.id,
            "name": item.name,
            "price": item.price,
            "stock": item.stock
        } for item in pagination.items]
    })


# 添加数据接口
@fspl_crud_bp.route('/api/product', methods=['POST'])
def add_product():
    data = request.get_json()
    try:
        product = Product(
            name=data['name'],
            price=float(data['price']),
            stock=int(data['stock'])
        )
        db.session.add(product)
        db.session.commit()
        return jsonify({"code": 0, "msg": "添加成功"})
    except IntegrityError:
        return jsonify({"code": 1, "msg": "数据已存在"}), 400
    except Exception as e:
        return jsonify({"code": 2, "msg": str(e)}), 500


# 更新数据接口
@fspl_crud_bp.route('/api/product/<int:id>', methods=['PUT'])
def update_product(id):
    product = Product.query.get_or_404(id)
    data = request.get_json()
    try:
        product.name = data['name']
        product.price = float(data['price'])
        product.stock = int(data['stock'])
        db.session.commit()
        return jsonify({"code": 0, "msg": "更新成功"})
    except Exception as e:
        return jsonify({"code": 1, "msg": str(e)}), 500


# 删除数据接口
@fspl_crud_bp.route('/api/product/<int:id>', methods=['DELETE'])
def delete_product(id):
    product = Product.query.get_or_404(id)
    try:
        db.session.delete(product)
        db.session.commit()
        return jsonify({"code": 0, "msg": "删除成功"})
    except Exception as e:
        return jsonify({"code": 1, "msg": str(e)}), 500
